package com.nbclass.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

/*
       AUTHOR: Jarvie -> YYDS
  CREATE TIME: 2024/9/13   
*/
@Configuration
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JdbcTokenRepositoryImpl jdbcTokenRepository;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //异常处理

        //token登录认证
        http.rememberMe().userDetailsService(userDetailsService).tokenRepository(jdbcTokenRepository).rememberMeParameter("jarvie").tokenValiditySeconds(3600*24*30);
        //表单验证
        http.formLogin().loginProcessingUrl("/loginForm").successForwardUrl("/main").loginPage("/Mylogin");
        //拦截
        http.authorizeRequests().antMatchers("/Mylogin").permitAll().anyRequest().authenticated();
        //设置响应头，允许跨域
        http.headers(headers->{
            headers.frameOptions(frameOptions->{
                frameOptions.sameOrigin();
            })
            ;});
//        http.headers().
        //配置自定义退出逻辑

        //关闭防护
        http.csrf().disable();
    }

    //配置记住我自动登录
    @Bean
    public JdbcTokenRepositoryImpl jdbcTokenRepository(DataSource dataSource){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
    //配置密码加密逻辑
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SessionRegistry mySessionRegistry(){
        return new SessionRegistryImpl();
    }
//    @Bean
//    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//        http.headers(headers->{
//            headers.frameOptions(frameOptions->{
//                frameOptions.sameOrigin();
//            })
//            ;});
//        return http.build();
//    }


}
